import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
import store from '@/store'

// API配置
const API_CONFIG = {
  // 开发环境
  development: {
    baseURL: 'http://localhost:8086/api',
    timeout: 15000
  },
  // 生产环境
  production: {
    baseURL: 'https://your-domain.com/api',
    timeout: 15000
  },
  // 测试环境
  test: {
    baseURL: 'https://test-api.your-domain.com/api',
    timeout: 15000
  }
}

// 获取当前环境配置
const getApiConfig = () => {
  const env = process.env.NODE_ENV || 'development'
  const envConfig = API_CONFIG[env]
  
  return {
    baseURL: process.env.VUE_APP_API_BASE_URL || envConfig.baseURL,
    timeout: envConfig.timeout
  }
}

// 创建axios实例
const service = axios.create(getApiConfig())

// request拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    // 对请求错误做些什么
    console.log(error)
    return Promise.reject(error)
  }
)

// response拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    
    // 如果返回的状态码不是200，说明接口有问题，把错误信息显示给用户
    if (response.status !== 200) {
      Message({
        message: res.message || '请求失败',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || '请求失败'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)
    
    // 处理401未授权错误
    if (error.response && error.response.status === 401) {
      Message({
        message: '登录已过期，请重新登录',
        type: 'error',
        duration: 5 * 1000
      })
      
      // 清除登录状态
      store.dispatch('logout')
      
      // 跳转到登录页
      router.push('/login')
    } else {
      Message({
        message: error.message || '网络错误',
        type: 'error',
        duration: 5 * 1000
      })
    }
    
    return Promise.reject(error)
  }
)

// 登录API
export function login(data) {
  return service({
    url: '/user/login',
    method: 'post',
    data
  })
}

// 登出API
export function logout() {
  return service({
    url: '/auth/logout',
    method: 'post'
  })
}

// 获取用户信息API
export function getUserInfo() {
  return service({
    url: '/auth/user-info',
    method: 'get'
  })
}

// 修改密码API
export function changePassword(data) {
  return service({
    url: '/auth/change-password',
    method: 'post',
    data
  })
}

// 知识分类相关API
// 获取分类列表
export function getCategoryPage(params) {
  return service({
    url: '/categories/page',
    method: 'get',
    params
  })
}


// 知识分类相关API
// 获取分类列表
export function getCategoryList(params) {
  return service({
    url: '/categories/list',
    method: 'get',
    params
  })
}

// 获取分类树形结构
export function getCategoryTree() {
  return service({
    url: '/categories/tree',
    method: 'get'
  })
}

// 获取分类详情
export function getCategoryDetail(id) {
  return service({
    url: `/categories/${id}`,
    method: 'get'
  })
}

// 新增分类
export function createCategory(data) {
  return service({
    url: '/categories',
    method: 'post',
    data
  })
}

// 更新分类
export function updateCategory(id, data) {
  return service({
    url: `/categories/${id}`,
    method: 'put',
    data
  })
}

// 删除分类
export function deleteCategory(id) {
  return service({
    url: `/categories/${id}`,
    method: 'delete'
  })
}

// 批量删除分类
export function batchDeleteCategories(ids) {
  return service({
    url: '/categories/batch-delete',
    method: 'delete',
    data: { ids }
  })
}

// 更新分类排序
export function updateCategorySort(data) {
  return service({
    url: '/categories/sort',
    method: 'put',
    data
  })
}

// 题目相关API
// 获取题目列表
export function getQuestionPage(params) {
  return service({
    url: '/questions/page',
    method: 'get',
    params
  })
}

// 获取题目详情
export function getQuestionDetail(id) {
  return service({
    url: `/questions/${id}`,
    method: 'get'
  })
}

// 新增题目
export function createQuestion(data) {
  return service({
    url: '/questions',
    method: 'post',
    data
  })
}

// 更新题目
export function updateQuestion(id, data) {
  return service({
    url: `/questions/${id}`,
    method: 'put',
    data
  })
}

// 删除题目
export function deleteQuestion(id) {
  return service({
    url: `/questions/${id}`,
    method: 'delete'
  })
}

// 批量删除题目
export function batchDeleteQuestions(ids) {
  return service({
    url: '/questions/batch-delete',
    method: 'delete',
    data: { ids }
  })
}

// 批量导入题目
export function importQuestions(data) {
  return service({
    url: '/questions/import',
    method: 'post',
    data,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 批量导出题目
export function exportQuestions(params) {
  return service({
    url: '/questions/export',
    method: 'get',
    params,
    responseType: 'blob'
  })
}

// 获取分类下的题目数量统计
export function getCategoryQuestionCount() {
  return service({
    url: '/questions/count',
    method: 'get'
  })
}

// 获取题目类型列表
export function getQuestionTypes() {
  return service({
    url: '/question-types/list',
    method: 'get'
  })
}

export default service
